﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ImageLoader.Resources;
using Windows.Storage;
using Microsoft.Xna.Framework.Media;
using System.IO.IsolatedStorage;
using System.IO;
using System.Threading.Tasks;

namespace ImageLoader
{
    public enum SaveLocation
    {
        CameraRoll,
        SavedPictures
    }

    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        //this is needed, since random NullReferenceExceptions can occur, but retrying usually works
        private void copyPhoto(IsolatedStorageFile isolatedStorage, MediaLibrary library, string folderName, string fileName, SaveLocation saveLocation)
        {
            using (IsolatedStorageFileStream fileStream = isolatedStorage.OpenFile(folderName + '\\' + fileName, FileMode.Open, FileAccess.Read))
            {
                int tryCount = 0;
                bool success = false;

                while ((!success) && (tryCount++ < 6))
                try
                {
                    fileStream.Position = 0;
                    if (saveLocation == SaveLocation.CameraRoll)
                        library.SavePictureToCameraRoll(fileName, fileStream);
                    else
                        library.SavePicture(fileName, fileStream);
                    success = true;
                }
                catch (Exception ex)
                {
                    tryCount++;
                }
            }
        }

        private async Task copyFolder(StorageFolder folder, SaveLocation saveLocation)
        {
            MediaLibrary library = new MediaLibrary();
            if (System.IO.Directory.Exists(folder.Path))
            {
                var files = await folder.GetFilesAsync();
                using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    foreach (var file in files)
                    {
                        if (file.Name.ToLower().EndsWith(".jpg"))
                            copyPhoto(isolatedStorage, library, folder.Path, file.Name, saveLocation);
                    }
                }

                var subFolders = await folder.GetFoldersAsync();
                foreach (var subFolder in subFolders)
                    await copyFolder(subFolder, saveLocation);
            }
        }

        private async void btnCameraRoll_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                StorageFolder cameraRollFolder = await localFolder.GetFolderAsync("CameraRoll");
                await copyFolder(cameraRollFolder, SaveLocation.CameraRoll);
                MessageBox.Show("Done");
            }
            catch (Exception)
            {
                MessageBox.Show("Error loading the images.  Make sure that isolated storage has been loaded.");
            }
        }

        private async void btnSavedPictures_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                StorageFolder cameraRollFolder = await localFolder.GetFolderAsync("SavedPictures");
                await copyFolder(cameraRollFolder, SaveLocation.SavedPictures);
                MessageBox.Show("Done");
            }
            catch (Exception)
            {
                MessageBox.Show("Error loading the images.  Make sure that isolated storage has been loaded.");
            }
        }
    }
}